package com.mxdx.edu.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.Digests;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.conf.RongcloudConfig;
import com.mxdx.edu.enums.CreateTypeEnums;
import com.mxdx.edu.enums.ErrorEnums;
import com.mxdx.edu.model.StudentGroupInfo;
import com.mxdx.edu.model.StudentGroupMember;
import com.mxdx.edu.model.StudentInfo;
import com.mxdx.edu.service.IStudentGroupService;
import com.mxdx.edu.service.IStudentService;
import com.mxdx.edu.util.ServletUtil;
import com.mxdx.edu.util.StringUtils;

import io.rong.models.Result;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;

/**
 * 移动端用户 即时通讯保存token信息
 * 
 * @author hjg
 *
 */

@Controller
@RequestMapping(value = "/api/user")
public class ApiUserController extends BaseController {

	private AppLogger logger = new AppLogger(ApiUserController.class);

	@Resource
	private IStudentService studentService;

	@Resource
	private IStudentGroupService studentGroupService;

	/**
	 * APP登陆
	 * 
	 * @param request
	 * @returnf
	 */
	@ResponseBody
	@RequestMapping(value = "/login")
	public ApiResult<Map<String, Object>> login(HttpServletRequest request, HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "login");
		ApiResult<Map<String, Object>> result = new ApiResult<>();
		Map<String, Object> resultMap = new HashMap<>();
		String phoneNumber = ServletUtil.getParameterStr(request, "phoneNumber", "");
		String password = ServletUtil.getParameterStr(request, "password", "");
		String remFlag = ServletUtil.getParameterStr(request, "remFlag", "");
		String studentType = ServletUtil.getParameterStr(request, "studentType", "");
		logger.doInfo("login", String.format("phoneNumber:%s, password:%s, remFlag:%s, studentType:%s", phoneNumber,
				password, remFlag, studentType));
		Map<String, Object> findMap = new HashMap<>();
		try {
			if (StringUtils.isAnyEmpty(phoneNumber, password)) {
				result.setStatus(ErrorEnums.MUST_FIELD_IS_NULL.getCode());
				result.setMessage(ErrorEnums.MUST_FIELD_IS_NULL.getDesc());
				return result;
			}

			password = Digests.md5(password);

			findMap.put("phoneNumber", phoneNumber);
			findMap.put("password", password);
			findMap.put("studentType", studentType);

			boolean checkLogin = studentService.checkLogin(findMap);
			if (!checkLogin) {
				result.setStatus(ErrorEnums.PHONE_AND_PASSWORD_FAIL.getCode());
				result.setMessage(ErrorEnums.PHONE_AND_PASSWORD_FAIL.getDesc());
				return result;
			}

			Map<String, Object> studentMap = studentService.findMapByPhoneNumberAndStudentType(phoneNumber,
					studentType);

			StudentInfo student = new StudentInfo();
			student.setId(studentMap.get("studentId").toString());
			student.setStudentName(studentMap.get("studentName").toString());
			student.setPersonProfile(String.valueOf(studentMap.get("headPortraitUrl")));

			String RongCloudToken = studentMap.get("token") == null ? "" : studentMap.get("token").toString();
			if (RongCloudToken.equals("")) {// 未注册融云
				RongCloudToken = RongcloudConfig.register(student);
				Map<String, Object> param = new HashMap<>();
				param.put("token", RongCloudToken);
				param.put("studentId", studentMap.get("studentId").toString());
				studentService.updateStudentInfoByMap(param);
			}

			resultMap.put("token", RongCloudToken);
			resultMap.put("stuId", studentMap.get("studentId").toString());
			resultMap.put("stuName", studentMap.get("studentName").toString());
			resultMap.put("mood", studentMap.get("mood").toString());
			resultMap.put("userInfo", studentMap);
			logger.info(ServletUtil.getClientIp(request));
		} catch (Exception e) {
			super.dealException(ErrorEnums.SYSTEM_ERROR, e, result, logger);
		}
		result.setResult(resultMap);
		return result;
	}

	/**
	 * 创建群组
	 * 
	 * @param request
	 * @param response
	 * @param stuGroup
	 *            -- groupName,userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/group/create")
	public ApiResult<Map<String, Object>> gcreate(StudentGroupInfo stuGroup, HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "/group/create");
		Map<String, Object> resultMap = new HashMap<>();
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		try {
			if(stuGroup.getGroupName()==null || stuGroup.getUserId()==null){
				apiResult.setStatus("11111111");
				apiResult.setMessage("error");
				apiResult.setInfo("群组名称和创建人不能为空！");
				return apiResult;
			}
			// 保存群组
			stuGroup.setCdate(new Date());
			String groupId = serialService.generateSerialNum(CreateTypeEnums.CREATE_GROUP.getCode(), 8);
			stuGroup.setId(groupId);
			stuGroup.setStatus("0");
			int count = studentGroupService.save(stuGroup);
			if (count > 0) {
				GroupModel groupModel = new GroupModel();
				groupModel.setName(stuGroup.getGroupName());
				groupModel.setId(groupId);
				// 创建人加入群组
				GroupMember[] members = { new GroupMember(stuGroup.getUserId(), groupId, 0) };
				groupModel.setMembers(members);

				StudentGroupMember sgm=new StudentGroupMember();
				sgm.setGroupId(groupId);
				sgm.setUserId(stuGroup.getUserId());
				sgm.setCdate(new Date());
				studentGroupService.saveMember(sgm);
				Result result = RongcloudConfig.createGroup(groupModel);
				if (result.getCode() == 200) {
					resultMap.put("groupId", groupId);
					resultMap.put("groupName", stuGroup.getGroupName());
					apiResult.setResult(resultMap);
				} else {
					apiResult.setStatus("11111111");
					apiResult.setMessage("error");
				}
			}
		} catch (Exception e) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			e.printStackTrace();
		}
		return apiResult;
	}

	/**
	 * 解散群组
	 * 
	 * @param stuGroup
	 *            ---id,userId
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/group/dismiss")
	public ApiResult<Map<String, Object>> gdismiss(StudentGroupInfo stuGroup, HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "/group/dismiss");
		Map<String, Object> resultMap = new HashMap<>();
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		try {
			if (stuGroup.getId() == null) {
				apiResult.setInfo("参数错误！");
				apiResult.setStatus("11111111");
				apiResult.setMessage("error");
				return apiResult;
			}
			stuGroup.setStatus("1");
			stuGroup.setUdate(new Date());
			// 保存群组
			int count = studentGroupService.update(stuGroup);
			if (count > 0) {
				GroupModel groupModel = new GroupModel();
				groupModel.setId(stuGroup.getId());
				GroupMember[] members = new GroupMember[] { new GroupMember().setId(stuGroup.getUserId()) };
				groupModel.setMembers(members);

				Result result = RongcloudConfig.dismissGroup(groupModel);
				if (result.getCode() == 200) {
					apiResult.setResult(resultMap);
				} else {
					apiResult.setStatus("11111111");
					apiResult.setMessage("error");
				}
			}
		} catch (Exception e) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			e.printStackTrace();
		}
		return apiResult;
	}

	/**
	 * 加入群组 群组人数不能超过3000人
	 * 
	 * @param request
	 * @param response
	 * @param stuGroup
	 *            -- groupName,userId,id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/group/join")
	public ApiResult<Map<String, Object>> gjoin(StudentGroupInfo stuGroup, HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "/group/join");
		Map<String, Object> paramMap = new HashMap<>();
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		try {

			if (stuGroup.getId() == null || stuGroup.getUserId() == null) {
				apiResult.setStatus("11111111");
				apiResult.setMessage("error");
				apiResult.setInfo("参数错误！");
				return apiResult;
			}

			paramMap.put("userId", stuGroup.getUserId());
			paramMap.put("groupId", stuGroup.getId());
			// 查询当前用户是否已经在群
			List<StudentGroupMember> list = studentGroupService.findList(paramMap);
			if (list != null && !list.isEmpty()) {
				apiResult.setInfo("您已经是群成员！");
				return apiResult;
			} else {
				paramMap.put("userId", null);
				paramMap.put("status", "0");
				list = studentGroupService.findList(paramMap);
				if (list != null && list.size() > 2999) {
					apiResult.setStatus("11111111");
					apiResult.setMessage("error");
					apiResult.setInfo("群组已满！");
					return apiResult;
				}
			}

			// 保存群组
			StudentGroupMember sgm = new StudentGroupMember();
			sgm.setGroupId(stuGroup.getId());
			sgm.setUserId(stuGroup.getUserId());
			int count = studentGroupService.saveMember(sgm);
			if (count > 0) {
				GroupModel groupModel = new GroupModel();
				groupModel.setName(stuGroup.getGroupName());
				groupModel.setId(stuGroup.getId());
				GroupMember[] members = { new GroupMember(stuGroup.getUserId(), stuGroup.getId(), 0) };
				groupModel.setMembers(members);

				Result result = RongcloudConfig.joinGroup(groupModel);
				if (result.getCode() == 200) {
					// apiResult.setResult(resultMap);
				} else {
					apiResult.setStatus("11111111");
					apiResult.setMessage("error");
				}
			}
		} catch (Exception e) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			e.printStackTrace();
		}
		return apiResult;
	}

	/**
	 * 退出群组
	 * 
	 * @param request
	 * @param response
	 * @param stuGroup
	 *            -- userId,id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/group/quit")
	public ApiResult<Map<String, Object>> gquit(StudentGroupInfo stuGroup, HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "/group/quit");
		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> paramMap = new HashMap<>();
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		if (stuGroup.getId() == null || stuGroup.getUserId() == null) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			apiResult.setInfo("参数错误！");
			return apiResult;
		}
		try {
			paramMap.put("userId", stuGroup.getUserId());
			paramMap.put("groupId", stuGroup.getId());
			paramMap.put("status", "1");
			int count = studentGroupService.updateStudentGroupMember(paramMap);
			if (count > 0) {
				GroupModel groupModel = new GroupModel();
				groupModel.setId(stuGroup.getId());
				GroupMember[] members = { new GroupMember(stuGroup.getUserId(), stuGroup.getId(), 0) };
				groupModel.setMembers(members);

				Result result = RongcloudConfig.quitGroup(groupModel);
				if (result.getCode() == 200) {
					apiResult.setResult(resultMap);
				} else {
					apiResult.setStatus("11111111");
					apiResult.setMessage("error");
				}
			}
		} catch (Exception e) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			e.printStackTrace();
		}
		return apiResult;
	}

	/**
	 * 群组用户列表
	 * 
	 * @param request
	 * @param response
	 * @param stuGroup
	 *            ---id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/group/userList")
	public ApiResult<List<Map<String,Object>>> gquery(StudentGroupInfo stuGroup, HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "/group/userList");
		ApiResult<List<Map<String,Object>>> apiResult = new ApiResult<>();
		try {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("groupId", stuGroup.getId());
			paramMap.put("status", "0");
			List<Map<String,Object>> list=  studentGroupService.findGroupUserList(paramMap);
			apiResult.setResult(list);
			
			/*GroupModel groupModel = new GroupModel();
			groupModel.setId(stuGroup.getId());
			GroupUserQueryResult result = RongcloudConfig.queryGroup(groupModel);
			if (result.getCode() == 200) {
				apiResult.setResult(result.getMembers());
			} else {
				apiResult.setStatus("11111111");
				apiResult.setMessage("error");
			}*/
		} catch (Exception e) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			e.printStackTrace();
		}
		return apiResult;
	}

	/**
	 * 更新群组
	 * 
	 * @param request
	 * @param response
	 * @param stuGroup
	 *            ---id,groupName
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/group/update")
	public ApiResult<Map<String, Object>> gupdate(StudentGroupInfo stuGroup, HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "/group/update");
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		Map<String, Object> resultMap = new HashMap<>();
		try {
			if (stuGroup.getId() == null) {
				apiResult.setStatus("11111111");
				apiResult.setMessage("error");
				apiResult.setInfo("参数错误！");
				return apiResult;
			}
			stuGroup.setUdate(new Date());
			int count = studentGroupService.update(stuGroup);
			if (count > 0) {
				GroupModel groupModel = new GroupModel();
				groupModel.setId(stuGroup.getId());
				groupModel.setName(stuGroup.getGroupName());
				Result result = RongcloudConfig.updateGroup(groupModel);
				if (result.getCode() == 200) {
					apiResult.setResult(resultMap);
				} else {
					apiResult.setStatus("11111111");
					apiResult.setMessage("error");
				}
			}
		} catch (Exception e) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			e.printStackTrace();
		}
		return apiResult;
	}
	
	
	/**
	 * 我的群组列表
	 * @param stuGroup
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/group/groupList")
	public ApiResult<List<Map<String,Object>>> glist(StudentGroupInfo stuGroup, HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "/group/groupList");
		ApiResult<List<Map<String,Object>>> apiResult = new ApiResult<>();
		try {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("userId", stuGroup.getUserId());
			paramMap.put("status", "0");
			List<Map<String,Object>> list=  studentGroupService.findGroupList(paramMap);
			apiResult.setResult(list);
		} catch (Exception e) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			e.printStackTrace();
		}
		return apiResult;
	}

	
	/**
	 * 查找群组
	 * @param stuGroup
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/group/search")
	public ApiResult<List<Map<String,Object>>> gsearch(StudentGroupInfo stuGroup, HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "/group/search");
		ApiResult<List<Map<String,Object>>> apiResult = new ApiResult<>();
		try {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("groupName", stuGroup.getGroupName());
			paramMap.put("status", "0");
			List<Map<String,Object>> list=  studentGroupService.findGroupList(paramMap);
			apiResult.setResult(list);
		} catch (Exception e) {
			apiResult.setStatus("11111111");
			apiResult.setMessage("error");
			e.printStackTrace();
		}
		return apiResult;
	}

}
